/**
 * 
 */
package com.newture.lxz.mail;

import java.io.File;
import java.time.temporal.ValueRange;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

import com.baymax.docx.util.LoggerKit;
import com.newture.lxz.db.model.LdMail;
import com.newture.lxz.generator.output.Column;
import com.newture.lxz.pvg.Pvg;
import com.newture.lxz.pvg.PvgUser;
import com.newture.lxz.services.impl.MailSrv;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author xiao.hu
 *
 */
public class BasicMail {

	@Autowired
	MailSrv mailSrv;
	protected MailConfig oMailConfig = new MailConfig();

	public void init() {
		oMailConfig.smtpHost = "smtp.163.com";
		oMailConfig.port = "465";
		oMailConfig.senderAddress = "roypierre@163.com";
		oMailConfig.senderAccount = "roypierre@163.com";
		oMailConfig.senderPassword = "lawdoc20190816";
		oMailConfig.company = "上海颐法信息技术有限公司";
		oMailConfig.home = "http://localhost:8081/lxzAdmin";
	}

	/**
	 * 发送邮件前，需要在mail表进行保存，然后统一由邮件定时服务发送邮件 同时，也为管理邮件提供可能。
	 */
	public void save(String domain, String param) {
		LdMail ldmail = new LdMail();
		ldmail.setDomain(domain);
		ldmail.setParam(param);
		ldmail.setContent(oMailConfig.content);
		ldmail.setRecipientAddress(oMailConfig.recipientAddress);
		ldmail.setSenderAddress(oMailConfig.senderAddress);
		ldmail.setStatus("pending");
		ldmail.setSubject(oMailConfig.subject);
		long newId = mailSrv.insert(ldmail);
		oMailConfig.id = newId;
	}

	/**
	 * 发送邮件，如果异常就是没有发送成功，不更改发送状态 如果无异常，则认为发送成功，更新邮件任务状态
	 * 因为邮件发送很慢，所以此为异步方法
	 */
	public void send() {
		// 两个线程的线程池
		ExecutorService executor = Executors.newFixedThreadPool(2);
		String pvgName = Pvg.getPvgName();
		// jdk1.8之前的实现方式
		CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
			@Override
			public String get() {
				LoggerKit.debug("task started!", "");
				PvgUser pvg = new PvgUser();
				pvg.setName(pvgName);
				Pvg.setPvg(pvg);
				sendMail();
				Pvg.removePvg();
				return "task finished!";
			}
		}, executor);

		// 采用lambada的实现方式
		future.thenAccept(e -> System.out.println(e + " ok"));
	}

	private void sendMail() {
		long mailId = oMailConfig.id;
		LdMail oLdMail = mailSrv.findById((int)mailId,
				new String[] { Column.ID, Column.VERSION, Column.LD_MAIL.TIMES });

		Mail mail = new Mail(oMailConfig);
		try {
			mail.send(null);
//			mailSrv.updateStatus(oLdMail.getId(), oLdMail.getVersion(),
//					ValueRange.ld_mail.status.sent.name(), oLdMail.getTimes());
		} catch (Exception e) {
			LoggerKit.error(e);
		}
	}
	
	/**
	 * 发送带附件的邮件
	 * @param zipFile
	 * @throws Exception
	 */
	public void sendMailWithAttachment(File zipFile) throws Exception {
		Mail mail = new Mail(oMailConfig);
		mail.send(zipFile);
	}
}
